﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Configuration;

using LoggingClient;

namespace ATMCommLib
{
    public class CommClient
    {
        private static Socket socketClient = null;
        IPEndPoint IPAddressEndP = null;
        ILogger mLogger = null;

        private void Init(ILogger logger, string ipAddress, int port)
        {
            try
            {
                mLogger = logger;

                IPAddress address;

                if (!IPAddress.TryParse(ipAddress, out address))
                {
                    throw new Exception("Invalid IP address!");
                }

                IPAddressEndP = new IPEndPoint(address, port);

                socketClient = new Socket(IPAddressEndP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                if (!socketClient.Connected)
                {
                    socketClient.Connect(IPAddressEndP);
                }
            }
            catch (Exception ex)
            {
                mLogger.Error(ex.ToString());
            }


        }

        public void WriteLine(byte[] content)
        {
            try
            {
                byte[] LenInfo = new byte[2];

                if (content == null)
                {
                    LenInfo[0] = 0;
                    LenInfo[1] = 0;
                }
                else if (content.Length == 1)
                {
                    LenInfo[0] = (byte)(content.Length / 256);
                    LenInfo[1] = 0;
                }
                else
                {
                    LenInfo[0] = (byte)(content.Length / 256);
                    LenInfo[1] = (byte)(content.Length % 256);
                }

                socketClient.Send(LenInfo);
                socketClient.Send(content);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public void WriteLine(string Str)
        {
            try
            {
                byte[] content = Encoding.UTF8.GetBytes(Str);
                byte[] LenInfo = new byte[2];

                if (content == null)
                {
                    LenInfo[0] = 0;
                    LenInfo[1] = 0;
                }
                else if (content.Length == 1)
                {
                    LenInfo[0] = (byte)(content.Length / 256);
                    LenInfo[1] = 0;
                }
                else
                {
                    LenInfo[0] = (byte)(content.Length / 256);
                    LenInfo[1] = (byte)(content.Length % 256);
                }

                socketClient.Send(LenInfo);
                socketClient.Send(content);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
